package com.springboot.jdbc.dao.impl;

import com.springboot.jdbc.dao.IUserDao;
import com.springboot.jdbc.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.swing.tree.TreePath;
import java.sql.*;

/**
 * @author liuwei
 * @version 2017/7/16 上午11:33
 * @modified TODO
 * @description 功能描述
 * @see
 * @since 1.0
 */
@Repository
public class UserDaoImpl implements IUserDao {
    @Autowired
    @Qualifier("primaryJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    @Override
    public User findById(Long id) {
        try {
            return jdbcTemplate.queryForObject("select * from t_user where id=?",new Object[]{id} , new UserRowMapper());
        }catch (DataAccessException e){
            return null;
        }
    }

    @Override
    public Long save(final User user) {
        final String sql = "insert into t_user(name,age,sex,createTime) values(?,?,?,NOW())";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator(){
            @Override
            public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
                PreparedStatement ps = conn.prepareStatement(sql, new String[] {});
                ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1,user.getName());
                ps.setInt(2, user.getAge());
                ps.setInt(3, user.getSex());
                return ps;
            }
        },keyHolder);
        return keyHolder.getKey().longValue();
//        return jdbcTemplate.update("insert into t_user(name,age,sex,createTime) values(?,?,?,NOW())",user.getName(),user.getAge(),user.getSex()) > 0;
    }

    @Override
    public Boolean update(User user) {
        return jdbcTemplate.update("update t_user set name=?,age=?,updateTime=NOW() where id=? and status=0",user.getName(),user.getAge(),user.getId()) > 0;
    }

    @Override
    public Boolean remove(Long id) {
        return null;
    }
}

class UserRowMapper implements RowMapper<User> {

    @Override
    public User mapRow(ResultSet rs, int rowNum) throws SQLException {
        User user = new User();
        user.setId(rs.getLong("id"));
        user.setName(rs.getString("name"));
        user.setAge(rs.getInt("age"));
        user.setSex(rs.getInt("sex"));
        user.setCreateTime(rs.getTime("createTime"));
        user.setUpdateTime(rs.getTime("updateTime"));
        return user;
    }
}